#include "StretchyLayout.h"

namespace Lame3d
{
	// StretchyLayout :: Properties //
	StretchyLayout::Properties::Properties(const Point2d &uL, const Point2d &lR)
			: upperLeft(uL), lowerRight(lR)
	{
	}
	
	StretchyLayout::Properties::~Properties()
	{
	}
	
	const Point2d& StretchyLayout::Properties::UpperLeft() const
	{
		return upperLeft;
	}
	
	const Point2d& StretchyLayout::Properties::LowerRight() const
	{
		return lowerRight;
	}
	
	// StretchyLayout //
	StretchyLayout::StretchyLayout()
	{
	}
	
	StretchyLayout::~StretchyLayout()
	{
		// Deletion of UIElements is handled by the Window.
		std::map<UIElement*, Properties*>::iterator it;
		for(it = properties.begin(); it != properties.end(); ++it) {
			delete it->second;
		}
	}
	
	void StretchyLayout::AddElement(UIElement *e, UILayoutProperties* props)
	{
		Properties *p = dynamic_cast<Properties*>(props);
		if(p == NULL) {
			throw "Invalid UILayoutProperties passed to StretchyLayout -- failed cast";
		}
		properties[e] = p;
	}
	
	void StretchyLayout::RemoveElement(UIElement *e)
	{
		std::map<UIElement*, Properties*>::iterator it;
		it = properties.find(e);
		if(it != properties.end()) {
			delete it->second;
			properties.erase(it);
		}
	}
	
	void StretchyLayout::Pack()
	{
		std::map<UIElement*, Properties*>::iterator it;
		for(it = properties.begin(); it != properties.end(); ++it) {
			align(it->first, it->second);
		}
	}
	
	void StretchyLayout::align(UIElement *e, Properties *p)
	{
		Point2d uLeft(p->UpperLeft());
		Point2d lRight(p->LowerRight());
		
		if(uLeft[0] < 0) {
			uLeft[0] += parentSize[0];
		}
		if(uLeft[1] < 0) {
			uLeft[1] += parentSize[1];
		}
		if(lRight[0] < 0) {
			lRight[0] += parentSize[0];
		}
		if(lRight[1] < 0) {
			lRight[1] += parentSize[1];
		}
		
		e->Location() = uLeft;
		lRight -= uLeft;
		e->Size() = lRight;
	}
}

// eof //
